package com.erpanderp.pr.model.entity

import org.springframework.dao.DataIntegrityViolationException

class UserController {

   static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        //redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def logout(){
            flash.message = "Goodbye ${session.user}"
            session.invalidate()
            redirect(action:"login")
        }


def approve(){
    def user = User.get(params.id)
    user.status= "Approved"
    user.lastUpdatedBy = session.user.email
     if (!user.save(flush: true)) {
            render(view: "show", id:params.id)
            return
        }

        sendMail {
            from "ERPandERP"
            to user.email
            subject "Account approved"
            text "Now you are ready to use your account" 
        }
}

/*Vijay Code*/
def resetPassword(){
        //render "UserName"+params.login
        /*String login = params.login
        session.login = login
        def user = User.findByEmployeeNumber(login)
        if(!user){
            flash.message = login + "is Not Valid"
            redirect(action:"login")
        }
        //render params.mailId + ":::::" + params.securityAnswer*/

    }

    def validateMail(){

        String mailId = params.mailId
        String accountId = params.accountId
        def user = User.findByEmailAndEmployeeNumber(mailId,accountId)
        if(user){
             def securityQuestion = user.securityQuestion
             session.securityQuestion = securityQuestion
            redirect(action:"validateIdentity",params: [securityQuestion: securityQuestion])
            //redirect(action:"validateIdentity")
        }
        else{
            flash.message = mailId + "   "+accountId + "  are not details "
            redirect(action:"resetPassword")

        }

    }
    def sendPassword(User user){
         sendMail {
            from "ERPandERP"
            to user.email
            subject "Request for New Password"
            text "###### is your new password login with the current password"
        }
    }

    def validateIdentity(){

    }
    def validateAnswer(){
         def securityAnswer = params.securityAnswer
        //render "secAns::"+securityAnswer+":::::"+"mailId"+session.mailId
        def user = User.findBySecurityQuestionAndSecurityAnswer(session.securityQuestion,securityAnswer)
        if(user){
            sendPassword(user)
            flash.message = "A new password has been sent to your registered email. Please change the password at your earliest convenience."
            redirect(action:"login")
        }else{
            def securityQuestion = session.securityQuestion
             flash.message = "Not a Valid Answer Try again"
            redirect(action:"validateIdentity",params: [securityQuestion: securityQuestion])
        }
    }
    def login(){

    }
    def register(){

    }


    def authenticate() {
        println "In the user authentication"
        def password = params.password.encodeAsSHA()
        def user = User.findByEmployeeNumberAndPassword(params.login,password)

      
        if(user){
            session.user = user
            flash.message = "Hello ${user.employeeNumber}!"
            response.sendRedirect("${request.contextPath}/")
        }else{
            flash.message = "Either your login id or password is incorrect. Please try again." 
            redirect(action:"login")
        }
    }
/*End of Vijay Code*/



def home(){

}

    def create() {

        def userInstance = new User(params)

        [userInstance:userInstance ]
    }

    def save() {
        def userInstance = new User(params)
        userInstance.roleName = "user"
        String createdBy = params.firstName +" " +params.lastName
        userInstance.createdBy = createdBy
        userInstance.lastUpdatedBy = createdBy

        //code for relational mapping

        def roleInstance = Role.findByAuthority(userInstance.roleName)
        println userInstance.roleName
        println roleInstance.id

        
        
        if (!userInstance.save(flush: true)) {
            println "Errors: " + userInstance.errors
            render(view: "create", model: [userInstance: userInstance])
            return
        }

        def userRoleInstance = new UserRole()
        userRoleInstance.user = userInstance
        userRoleInstance.role = roleInstance
        roleInstance.addToUserRoles(userRoleInstance)
        userInstance.addToUserRoles(userRoleInstance)
        userRoleInstance.save()

        sendMail {
            from "ERPandERP"
            to "vijayasarathi22@gmail.com"
            subject "Request for New Password"
            text "A new password has been created"
        }

        flash.message = "Your new account is registered successfully and is waiting for approval. You will be receiving an email after your account is approved. "
        //redirect(action: "show", id: userInstance.id)
        redirect(action:"login")
    }

    def show(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def edit(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def update(Long id, Long version) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (userInstance.version > version) {
                userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'user.label', default: 'User')] as Object[],
                          "Another user has updated this User while you were editing")
                render(view: "edit", model: [userInstance: userInstance])
                return
            }
        }

        userInstance.properties = params

        if (!userInstance.save(flush: true)) {
            render(view: "edit", model: [userInstance: userInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def delete(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        try {
            userInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "show", id: id)
        }
    }
}
